package com.buy.controller;

import com.buy.exception.MsgException;
import com.buy.service.InstantBuyService;
import com.common.VO.SysResult;
import com.common.domain.InstantBuyItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-25 8:56
 * @description
 * @copyright 2021
 */
@RestController
@RequestMapping("/instant")
public class InstantBuyController {
  @Autowired private InstantBuyService instantBuyService;

  /**
   * 查询所有秒杀商品
   *
   * @return 秒杀商品列表
   */
  @RequestMapping("/manage/list")
  @ResponseBody
  public List<InstantBuyItem> queryItems() {
    return instantBuyService.queryItems();
  }

  /**
   * 查询单个秒杀商品
   *
   * @param itemId 商品ID
   * @return
   */
  @RequestMapping("/manage/{itemId}")
  @ResponseBody
  public InstantBuyItem queryItem(@RequestParam("itemId") String itemId) {
    return instantBuyService.queryItem(itemId);
  }

  @RequestMapping("/manage/{itemId}/{userName}")
  @ResponseBody
  public SysResult startBuy(
      @RequestParam("itemId") String itemId, @RequestParam("userName") String userName) {
    try {
      if (userName == null) {
        throw new MsgException("当前用户未登录");
      }
      instantBuyService.startBuy(itemId, userName);
      return SysResult.ok();
    } catch (MsgException e) {
      e.printStackTrace();
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      e.printStackTrace();
      return SysResult.build(500, e.getMessage(), e);
    }
  }
}
